﻿using System;

namespace _28._实现_strStr__
{
    /// <summary>
    /// https://leetcode.cn/problems/implement-strstr/
    /// </summary>
    public class Solution
    {
        public int StrStr(string haystack, string needle)
        {
            if (needle.Length == 0) return 0;
            return haystack.IndexOf(needle);
        }

        public int StrStr2(string haystack, string needle)
        {
            if (needle.Length == 0) return 0;

            for (int i = 0; i < haystack.Length; i++)
            {
                int j = 0;
                for (; j < needle.Length && i + j < haystack.Length;)
                {
                    if (haystack[i + j] == needle[j])
                    {
                        j++;
                    }
                    else
                    {
                        break;
                    }
                }
                if (j == needle.Length)
                {
                    return i;
                }
            }

            return -1;
        }
        public int StrStr3(string haystack, string needle)
        {
            if (needle.Length == 0) return 0;

            for (int i = 0; i <= haystack.Length - needle.Length; i++)
            {
                int j = 0;
                for (; j < needle.Length && i + j < haystack.Length; j++)
                {
                    if (haystack[i + j] != needle[j]) break;
                }
                if (j == needle.Length)
                {
                    return i;
                }
            }

            return -1;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(new Solution().StrStr("hello", "ll"));
            Console.WriteLine(new Solution().StrStr("aaaaa", "bba"));
            Console.WriteLine(new Solution().StrStr("", ""));
            Console.WriteLine();
            Console.WriteLine(new Solution().StrStr2("hello", "ll"));
            Console.WriteLine(new Solution().StrStr2("aaaaa", "bba"));
            Console.WriteLine(new Solution().StrStr2("", ""));
            Console.WriteLine();
            Console.WriteLine(new Solution().StrStr3("hello", "ll"));
            Console.WriteLine(new Solution().StrStr3("aaaaa", "bba"));
            Console.WriteLine(new Solution().StrStr3("", ""));
        }
    }
}
